#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

#define RD 0
#define WR 1

int
main(int argc, char *argv[]){
    
    int p2c[2];
    int c2p[2];
    pipe(p2c);
    pipe(c2p);

    char *buf = (char *)malloc(sizeof(char));

    int pid = fork();
    
    if (pid>0) { // parent process
        close(p2c[RD]);
        close(c2p[WR]);
        if(buf){
            if(write(p2c[WR], buf, sizeof(char))!=sizeof(char)){
                fprintf(2, "ERROR: parent wirte()!\n");
                exit(1);
            }

            if(read(c2p[RD], buf, sizeof(char))!=sizeof(char)){
                fprintf(2, "ERROR: parent read()!\n");
                exit(1);
            } else {
                printf("%d: received pong\n", getpid());
            }
        }
        close(p2c[WR]);
        close(c2p[RD]);
    } else if (pid==0) { // child process
        close(p2c[WR]);
        close(c2p[RD]);
        if(buf){
            if(read(p2c[RD], buf, sizeof(char))!=sizeof(char)){
                fprintf(2, "ERROR: child read()!\n");
                exit(1);
            } else {
                printf("%d: received ping\n", getpid());
            }

            if(write(c2p[WR], buf, sizeof(char))!=sizeof(char)){
                fprintf(2, "ERROR: child write()!\n");
                exit(1);
            }
        }
        close(p2c[RD]);
        close(c2p[WR]);
    } else {
        close(p2c[RD]);
        close(p2c[WR]);
        close(c2p[RD]);
        close(c2p[WR]);
        fprintf(2, "ERROR: fork()!\n");
    }
    if(buf){
        free(buf);
    }
    exit(0);
}